/**
 * 布局-Header区块
 *
 */
 const tpCommonLayoutHeader = {
    props: {
        option: {
            type: Object,
            default: function() {
                return {
                    /* background:"#1c1d22",//背景色
                    userMenubackground:"#0f1115 !important", //用户二级菜单背景色
                    layout:"dropdown", //指定布局["dropdown","inline"],默认为dropdown
                    logoConf:{
                        logoUrl:"", // logo图片地址
                        logoLabel:""  // logo的文字
                    }*/
                };
            }
        }
    },
    data() {
        return {
            dialog: {
                editPaw: {
                    show: false
                }
            },
            username: ''
        };
    },
    template: `<div class="common-layout-header" :style="{background:option.background || '#1c1d22'}">
                    <div class="logo">
                        <slot name="logo">
                            <template v-if="option.logoConf">
                                <img v-if="option.logoConf.logoUrl" :src="option.logoConf.logoUrl" ondragstart="return false;">
                                <span>{{option.logoConf.logoLabel}}</span>
                            </template> 
                        </slot>
                    </div>
                    <div class="fl">
                        <slot name="left"></slot>
                    </div>
                    <div class="fr" style="height: 50px;display: flex;">
                        <slot name="right">
                            <div class="userInfo">                               
                                <el-dropdown @command="userOperation">
                                    <span class="user tp-layout-header__user"><div class="custom-icon-user" :style="userIconStyle"></div>{{currentUsername}}<i class="el-icon-arrow-down el-icon--right"></i></span>
                                    <el-dropdown-menu slot="dropdown" class="tp-layout-header-operation" :style="{background:option.userMenubackground || '#0f1115'}">
                                        <el-dropdown-item command="editPaw">修改密码</el-dropdown-item>
                                        <el-dropdown-item command="logout">退出</el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>                                 
                            </div>
                            <tp-mod-passwd v-model="dialog.editPaw.show"></tp-mod-passwd> 
                        </slot>
                    </div>
                    <div class="fr">
                        <slot name="center">
                            <slot name="nav"></slot>
                        </slot>
                    </div>
    </div>`,
    computed: {
        // 根据布局设置logo的class
        currentLogo() {
            const layout = this.currentOperationStyle;
            return 'logo ' + layout;
        },
        userInfo() {
            const userInfo = tpSaaSCore.getUserInfo();
            return userInfo || {};
        },
        currentUsername() {
            const {
                trueName,
                userName
            } = tpSaaSCore.getUserDetails() || {};
            return trueName || userName;
        },
        // 根据props参数设置布局，默认采用dropdown布局
        currentOperationStyle() {
            const layout = this.option.layout || '';
            const layoutArr = ['inline'];
            // 检查operationStyle值是否有效
            if (layoutArr.includes(layout)) {
                return layout;
            }
            return 'dropdown';
        },
        userIconStyle() {
            const {
                icon,
                photo,
                sex = 1
            } = this.userInfo.userDetails || {};
            const userIcon = icon || (photo || (sex == 1
                ? 'https://cdn.static.zjtpyun.com/common/images/male.png'
                : 'https://cdn.static.zjtpyun.com/common/images/female.png'));
            return {
                'background': "url('" + userIcon + "')",
                'background-size': 'cover'
            };
        }
    },
    methods: {
        userOperation(command) {
            switch (command) {
                case 'logout':
                    this.logout();
                    break;
                case 'editPaw':
                    this.dialog.editPaw.show = true;
                    break;
            }
        },
        logout() {
            const currentHref = location.href;
            location.href = this.userInfo.logoutURL + '?refererURL=' + currentHref;
        }
    }
};
Vue.component('TpCommonLayoutHeader', tpCommonLayoutHeader);
/**
 * 左侧导航菜单项
 */
const tpCommonLeftNavItem = {
    props: {
        option: {
            type: Object,
            default: function() {
                return {
                    /*
                    nameField :"name",
                    pathField :"path",
                    item: {
                         path: '', //path与child不能同时出现
                         name: '',//菜单名称
                         icon:'',
                         child: [
                             {
                                 path: '',//菜单链接
                                 name: '',//菜单名称
                                 icon:'',
                                 permission: ['op_mod']//菜单权限
                             }
                         ]
                     },
                     navIndex: ""//菜单标识
                     */
                };
            }
        }
    },
    data() {
        return {
            showTimeout: 0,
            hideTimeout: 0
        };
    },
    template: `<el-submenu :show-timeout="showTimeout" :hide-timeout="hideTimeout" v-if="option.item[option.childrenField] && option.item[option.childrenField].length" :index="option.item[option.pathField]+'$_$'+option.item[option.nameField]+'$_$'+option.item[option.uuidField]" :popper-class="option.customClass" :popper-append-to-body="true">
                    <!-- 创建父级菜单 -->
                    <template slot="title">
                        <i v-if="option.item.icon && option.showIcon" :class="option.item.icon"></i>
                        <span :style="option.dirActive?'color: #0096ff !important;':''">{{ option.item[option.nameField] }}</span>
                    </template>
                    <!-- 创建子菜单 -->
                    <tp-common-left-nav-item v-for="(subItem,i) in option.item[option.childrenField]" :option="currentOption(subItem,option.navIndex,i)" :key="subItem[option.uuidField]+'_'+subItem.id"></tp-common-left-nav-item>
                </el-submenu>
                <el-menu-item v-else :index="option.item[option.pathField]">
                    <i v-if="option.item.icon && option.showIcon" :class="option.item.icon"></i>
                    <span slot="title" class="menu-item_titlelabel" :title="option.item[option.nameField]">{{option.item[option.nameField]}}</span>
                    <slot name="op" :data="option"></slot>                     
                </el-menu-item>`,
    methods: {
        currentOption(item, parentIdnex, index) {
            if (!item.path) {
                item.path = '#' + md5(JSON.stringify(item));
            }
            return {
                customClass: this.option.customClass,
                nameField: this.option.nameField,
                pathField: this.option.pathField,
                childrenField: this.option.childrenField,
                uuidField: this.option.uuidField,
                item: item,
                showIcon: this.option.showIcon,
                navIndex: parentIdnex + '-' + index
            };
        },
        currentKey(item, parentIdnex, index) {
            return parentIdnex + '-' + index;
        }
    }
};
Vue.component('TpCommonLeftNavItem', tpCommonLeftNavItem);
/**
 * 左侧导航菜单
 */
const tpCommonLeftNav = {
    props: {
        option: {
            type: Object,
            default: function() {
                return {
                    /*
                    nameField :"name",
                    pathField :"path",
                    childrenField :"children",
                    apiurl:"",
                    showIcon:false, //是否显示菜单图标
                    uuidField:"code" //唯一标识字段
                    */
                };
            }
        }
    },
    data() {
        return {
            // isCollapse: false,
            overClass: '', // 收缩或展开的className
            menuShow: true, // 菜单是否展开
            menuWidth: 0, // 菜单展开的宽度
            showOpBtn: false, // 是否显示操作按钮
            count: 0, // 拖拽下标标记
            draggable: false, // 是否进入拖拽状态
            loaded: false, // API请求结果状态
            flatNavList: [],
            activeDir: []
        };
    },
    template: `<div class="has-logo" :class="currentLayout" :style="{ backgroundColor: option.menuConf.backgroundColor }">
    <div class="sidebar-logo-container">
        <h1 v-show="sidebar.opened" class="sidebar-title">{{ option.logoConf.logoLabel }}</h1>
    </div>
    <el-scrollbar wrap-class="scrollbar-wrapper">
        <el-menu ref="navbar" :collapse-transition="false" :default-active="defActive" :mode="navMode" menu-trigger="hover" @select="selectMenu" unique-opened :background-color="option.menuConf.backgroundColor" :text-color="option.menuConf.textColor" :active-text-color="option.menuConf.activeTextColor" :collapse="isCollapse" @open="openHandle"  @close="openHandle">
            <template v-for="(item, index) in allRows" :key="item[currentUuidField]+'_'+item.id">
                <el-menu-item-group v-if="item.group && item.group.title">
                    <div slot="title">{{item.group.title}}</div>
                    <tp-common-left-nav-item v-for="(groupItem, groupindex) in item.group.list" :key="groupItem[currentUuidField]+'_'+groupItem.id" :option="currentOption(groupItem,String(index+''+groupindex))"></tp-common-left-nav-item>
                </el-menu-item-group>
                <tp-common-left-nav-item v-else :option="currentOption(item,String(index))"></tp-common-left-nav-item>
            </template>
            <slot name="custom"></slot>
        </el-menu>
    </el-scrollbar>
    <!--<div v-if="currentShowSwitch" class="switch" @click="switchShowStatus"><span><i :class="switchIcon"></i></span></div>-->
</div>`,
    computed: {
        sidebar() {
            return layoutState.sidebar;
        },
        isCollapse() {
            return !this.sidebar.opened;
        },
        /**
         * 激活的菜单项
         */
        defActive() {
            const thiz = this;
            if (this.activeDir && this.activeDir.length) {
                return null;
            }
            const locationPathname = window.location.href;
            // 存储当前激活菜单地址的key
            const {
                cacheKeyPrefix = ''
            } = window.GLOBAL_CONFIG || {};
            const _cacheKey = md5(cacheKeyPrefix + '_virtualPath') + '_nav-level2';
            const _customParamCode = MACRO_VARIABLE.CURRENTURL_PARAM('menuCode');
            function loopHandle(rows) {
                let row;
                let rowPath;
                for (const idx in rows) {
                    row = rows[idx];
                    if (row['group'] != undefined) {
                        const matchRow = loopHandle(row['group'].list);
                        if (matchRow) {
                            tpLocalStorage.set(_cacheKey, matchRow);
                            return matchRow;
                        }
                    } else if (row[thiz.currentChildrenField] != undefined && row[thiz.currentChildrenField].length) {
                        const matchRow = loopHandle(row[thiz.currentChildrenField]);
                        if (matchRow) {
                            tpLocalStorage.set(_cacheKey, matchRow);
                            return matchRow;
                        }
                    } else if (_customParamCode) {
                        if (row[thiz.currentUuidField] == _customParamCode) {
                            tpLocalStorage.set(_cacheKey, row);
                            return row;
                        }
                    } else {
                        rowPath = row.path.replace(/[.]+[/]/g, '');
                        if (rowPath.indexOf('http') == 0) {
                            rowPath = rowPath.substring(rowPath.indexOf('/'));
                        }
                        // if (rowPath.indexOf("?")) {
                        //     rowPath = rowPath.split("?")[0];
                        // }
                        if (locationPathname.indexOf(rowPath) != -1) {
                            tpLocalStorage.set(_cacheKey, row);
                            return row;
                        }
                    }
                }
                return null;
            }
            // URL匹配
            let match_row = loopHandle(this.rows) || null;
            // 上一次打开的菜单地址缓存匹配
            if (!match_row && MACRO_VARIABLE.CURRENTURL_PARAM('useCacheActive')) {
                match_row = tpLocalStorage.get(_cacheKey, '[]');
                if (Object.prototype.toString.call(match_row) == '[object Array]') {
                    match_row = null;
                }
            }
            // 去除缓存URL中的双引号
            if (match_row) {
                if (match_row['custom_child']) {
                    bus.$emit('current-menu-position', {
                        position: match_row.position,
                        custom_child: match_row['custom_child']
                    });
                } else {
                    bus.$emit('current-menu-position', {
                        position: match_row.position
                    });
                }
                return match_row.path.replace(/["]/g, '');
            }
            return null;
        },
        allRows() {
            return this.rows;
        },
        /**
         * 菜单布局
         * @returns {string}
         */
        currentLayout() {
            return 'left ' + this.overClass;
        },
        /**
         * 菜单展开模式
         * @returns {string}
         */
        navMode() {
            return 'vertical';
        },
        /**
         * 菜单名称映射字段
         * @returns {*|string}
         */
        currentNameField: function() {
            return this.$computedStringValue(this.option.nameField, 'name');
        },
        /**
         * 菜单地址映射字段
         * @returns {*|string}
         */
        currentPathField: function() {
            return this.$computedStringValue(this.option.pathField, 'path');
        },
        /**
         * 子菜单映射字段
         * @returns {*|string}
         */
        currentChildrenField: function() {
            return this.$computedStringValue(this.option.childrenField, 'child');
        },
        /**
         * 图标映射字段
         * @returns {*|string}
         */
        currentIconField: function() {
            return this.$computedStringValue(this.option.iconField, 'icon');
        },
        /**
         * 唯一标识字段
         */
        currentUuidField() {
            return this.$computedStringValue(this.option.uuidField, 'code');
        },
        /**
         * 是否显示菜单图标
         * @returns {*}
         */
        currentShowIcon() {
            return this.$computedBooleanValue(this.option.showIcon, false);
        },
        /**
         * 是否显示菜单隐藏、显示开关
         * @returns {*}
         */
        currentShowSwitch() {
            return this.$computedBooleanValue(this.option.showSwitch, false);
        },
        /**
         * 收缩或展开图标
         * @returns {*|string}
         */
        switchIcon() {
            if (this.menuShow) {
                return this.$computedStringValue(this.option.switchOpenedIcon, 'el-icon-d-arrow-left');
            }
            return this.$computedStringValue(this.option.switchClosedIcon, 'el-icon-d-arrow-right');
        }
    },
    methods: {
        /**
         * 菜单项option
         * @param item
         * @param index
         */
        currentOption(item, index) {
            if (!item[this.currentPathField]) {
                item[this.currentPathField] = '#' + md5(JSON.stringify(item));
            }
            return {
                customClass: 'tp-nav-left',
                nameField: this.currentNameField,
                pathField: this.currentPathField,
                childrenField: this.currentChildrenField,
                uuidField: this.currentUuidField,
                item: item,
                showIcon: this.currentShowIcon,
                navIndex: index,
                dirActive: this.activeDir && this.activeDir.includes(item[this.currentUuidField])
            };
        },
        /**
         * 菜单被选中
         * @param index
         * @param indexPath
         */
        selectMenu(index, indexPath) {
            this.activeDir = [];
            window.location.href = this.$aHrefHandle(index, {});
        },
        /**
         * 目录展开
         * @param index
         * @param indexPath
         */
        openHandle(index, indexPath) {
            const url = index.split('$_$')[0];
            if (url == '#' || url == 'javascript:void(0)') {
                // 暂不作处理
            } else {
                const menuName = index.split('$_$')[1];
                const menuCode = index.split('$_$')[2];
                if (this.activeDir && this.activeDir.length && this.activeDir.includes(menuCode)) {
                    return;
                }
                this.activeDir = [index.split('$_$')[2]];
                bus.$emit('open-menu-dir-page', {
                    tabname: menuName,
                    iframeOption: {
                        name: md5(menuName),
                        url: this.$aHrefHandle(url, {
                            layout_type: 2
                        })
                    }
                });
            }
        },
        /**
         * 收缩或展开按钮
         */
        switchShowStatus() {
            if (this.menuShow) {
                if (this.menuWidth == 0) {
                    this.menuWidth = this.$refs.navbar.$el.offsetWidth;
                }
                this.$refs.navbar.$el.style.maxWidth = '0px';
            } else {
                this.$refs.navbar.$el.style.maxWidth = this.menuWidth + 'px';
            }
            this.menuShow = !this.menuShow;
        },
        /**
         * 数据加载完毕
         * @param rows
         */
        loadedDataCallback: function(rows) {
            this.loaded = true;
        }
    },
    components: {
        tpCommonLeftNavItem
    },
    extends: tpWebuiBase
};
Vue.component('TpCommonLeftNav', tpCommonLeftNav);

const layoutState = Vue.observable({
    sidebar: {
        opened: true
    }
});

Vue.component('TpNavbar', {
    computed: {
        sidebar() {
            return layoutState.sidebar;
        },
        isCollapse() {
            return !this.sidebar.opened;
        },
        userInfo() {
            const userInfo = tpSaaSCore.getUserInfo();
            return userInfo || {};
        },
        currentUsername() {
            const {
                trueName,
                userName
            } = tpSaaSCore.getUserDetails() || {};
            return trueName || userName;
        },
        // 根据props参数设置布局，默认采用dropdown布局
        currentOperationStyle() {
            const layout = this.option.layout || '';
            const layoutArr = ['inline'];
            // 检查operationStyle值是否有效
            if (layoutArr.includes(layout)) {
                return layout;
            }
            return 'dropdown';
        },
        userIconStyle() {
            const {
                icon,
                photo,
                sex = 1
            } = this.userInfo.userDetails || {};
            const userIcon = icon || (photo || (sex == 1
                ? 'https://cdn.static.zjtpyun.com/common/images/male.png'
                : 'https://cdn.static.zjtpyun.com/common/images/female.png'));
            return {
                'background': "url('" + userIcon + "')",
                'background-size': 'cover'
            };
        }
    },
    methods: {
        toggleSideBar() {
            this.sidebar.opened = !this.sidebar.opened;
        },
        userOperation(command) {
            switch (command) {
                case 'logout':
                    this.logout();
                    break;
                case 'editPaw':
                    this.$emit('edit-paw');
                    break;
            }
        },
        logout() {
            const currentHref = location.href;
            location.href = this.userInfo.logoutURL + '?refererURL=' + currentHref;
        }
    },
    template: `<div class="navbar">
        <hamburger id="hamburger-container" :is-active="sidebar.opened" class="hamburger-container" @toggle-click="toggleSideBar"></hamburger>
        <slot name="breadcrumb"></slot>
        <div class="right-menu">
            <el-dropdown class="avatar-container right-menu-item hover-effect" trigger="click">
                <div class="avatar-wrapper">
                    <div class="custom-icon-user" :style="userIconStyle"></div>
                    <span v-html="currentUsername || '&nbsp;'" class="username"></span>
                    <i class="el-icon-arrow-down"></i>
                </div>
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item @click.native="userOperation('editPaw')">修改密码</el-dropdown-item>
                    <el-dropdown-item divided @click.native="userOperation('logout')">
                        <span style="display: block;">退出</span>
                    </el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
        </div>
    </div>`
});

Vue.component('Hamburger', {
    props: {
        isActive: {
            type: Boolean,
            default: false
        }
    },
    methods: {
        toggleClick() {
            this.$emit('toggle-click');
        },
    },
    template: `<div style="padding: 0 15px;" @click="toggleClick">
    <svg
      :class="{'is-active':isActive}"
      class="hamburger"
      viewBox="0 0 1024 1024"
      xmlns="http://www.w3.org/2000/svg"
      width="64"
      height="64"
    >
      <path d="M408 442h480c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8H408c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8zm-8 204c0 4.4 3.6 8 8 8h480c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8H408c-4.4 0-8 3.6-8 8v56zm504-486H120c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zm0 632H120c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h784c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zM142.4 642.1L298.7 519a8.84 8.84 0 0 0 0-13.9L142.4 381.9c-5.8-4.6-14.4-.5-14.4 6.9v246.3a8.9 8.9 0 0 0 14.4 7z"></path>
    </svg>
  </div>`
});

/**
 * 布局框架
 */
const templateLayout2 = {
    props: {
        background: {
            type: String,
            default: '#272b34' // "#334971"
        },
        layoutContentClass: {
            type: String,
            default: 'manage-grid'
        },
        leftNavShow: {
            type: Boolean,
            default: true
        },
    },
    data() {
        const {
            userDetails = {}
        } = tpSaaSCore.getUserInfo() || {};
        const sysConf = userDetails.sysConf || {
            logo: '',
            sysName: ''
        };
        return {
            headerOption: {
                background: '#272b34',
                logoConf: {
                    logoUrl: sysConf.logo || '../../resources/img/logo.png',
                    logoLabel: sysConf.sysName || '托普 • 数智农业云运维管理系统'
                }
            },
            leftNavOption: {
                showSwitch: true,
                showIcon: true,
                apiurl: GLOBAL_CONFIG.menuApiurl || "user/auth/getMenuList/1",
                logoConf: Object.assign({
                    logoUrl: sysConf.logo || '../../resources/img/logo.png',
                    logoLabel: sysConf.sysName || '水稻所'
                }, GLOBAL_CONFIG.logoConf || {}),
                menuConf: Object.assign({
                    backgroundColor: '#ffffff',
                    textColor: '#303133',
                    activeTextColor: '#409EFF',
                }, GLOBAL_CONFIG.menuConf || {}),
            },
            // 隐藏模板的header和body-left(值为真表示隐藏，且值为11表示当前会话下都隐藏,否则表示当前页面隐藏)
            hiddenLayout: MACRO_VARIABLE.CURRENTURL_PARAM('hidden_layout') || sessionStorage.getItem('hidden_layout') || 0,

            dialog: {
                editPaw: {
                    show: false
                }
            },

            fixedHeaderHeight: 50,
        };
    },
    template: `<div :class="classObj" class="app-wrapper">
        <tp-common-left-nav v-show="!hiddenLayout" v-if="leftNavShow" :option='leftNavOption' class="sidebar-container"></tp-common-left-nav>
        <div class="main-container">
            <div ref="fixed-header" class="fixed-header">
                <tp-navbar @edit-paw="editPaw"><slot slot="breadcrumb" name="breadcrumb"></slot></tp-navbar>
                <slot name="navbar-after"></slot>
            </div>
            <div class="page-content" :style="{ paddingTop: fixedHeaderHeight + 'px' }"><slot></slot></div>
        </div>
        <tp-mod-passwd v-model="dialog.editPaw.show"></tp-mod-passwd>
    </div>`,
    computed: {
        currentPositionTop() {
            if (this.hiddenLayout) {
                if (this.hiddenLayout == 11) {
                    sessionStorage.setItem('hidden_layout', this.hiddenLayout);
                } else {
                    sessionStorage.removeItem('hidden_layout');
                }
                return {
                    top: 0
                };
            }
            sessionStorage.removeItem('hidden_layout');
            return {};
        },
        sidebar() {
            return layoutState.sidebar;
        },
        classObj() {
            return {
                hideSidebar: !this.sidebar.opened,
                openSidebar: this.sidebar.opened
            };
        },
    },
    mounted() {
        this.fixedHeaderHeight = this.$refs['fixed-header'].offsetHeight;
    },
    methods: {
        editPaw() {
            this.dialog.editPaw.show = true;
        }
    }
};
Vue.component('TemplateLayout2', templateLayout2);
/**
 * 布局框架二次封装
 */
const templateLayout = {
    props: {
        tabsOption: {
            type: Object,
            default: function() {
                return {};
            }
        }
    },
    data() {
        return {
            layoutType: MACRO_VARIABLE.CURRENTURL_PARAM('layout_type') || 1,
            tabs2Option: this.$root.tabsOption,
            showIframe: false,
            iframeOption: {}
        };
    },
    template: `<template-layout2 v-if="layoutType==1" id="app" v-cloak class="custom-layout-ext">
    <template v-if="tabs2Option && tabs2Option.tabs && tabs2Option.tabs.length">
        <tp-tabs2 v-if="!showIframe" ref="tabs2" :option='tabs2Option'>
            <slot slot="tab1" name="tab1"></slot>
        </tp-tabs2>
        <tp-tabs2 v-else ref="tabs2" :option='tabs2Option' class="useIframe">
            <tp-iframe slot="tab1" :name="iframeOption.name" :url="iframeOption.url"></tp-iframe>
        </tp-tabs2>
    </template>
    <slot v-else></slot>
    <slot slot="breadcrumb" name="breadcrumb"></slot>
    <slot slot="navbar-after" name="navbar-after"></slot>
</template-layout2>
<div v-else id="app" v-cloak class="common-layout-body inner"><!--不使用layout-->
    <slot name="tab1"></slot>
</div>`,
    created() {
        bus.$on('open-menu-dir-page', (msg) => {
            this.showIframe = true;
            this.iframeOption = msg.iframeOption;
            const tabname = tpURLParam.get('tabname', this.iframeOption.url) || msg.tabname;
            this.tabs2Option = {
                activeName: 'tab1',
                tabs: [
                    {
                        name: 'tab1',
                        label: tabname
                    }
                ]
            };
        });
    }
};
Vue.component('TemplateLayout', templateLayout);
